package com.ffapp.demo.chat;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.services.core.PoiItem;
import com.ffapp.demo.R;
import com.ffapp.demo.basis.BasisActivity;
import com.ffapp.demo.basis.Constants;
import com.ffapp.demo.bean.BaseListBeanXF;
import com.ffapp.demo.bean.BasisBean;
import com.ffapp.demo.bean.BusiTypeEmum;
import com.ffapp.demo.bean.CommonMsgListBean;
import com.ffapp.demo.bean.CommonMsgListData;
import com.ffapp.demo.bean.FileTypeEmum;
import com.ffapp.demo.bean.LoginBean;
import com.ffapp.demo.bean.UserUploadFileBean;
import com.ffapp.demo.bean.UserUploadFileListBean;
import com.ffapp.demo.chat.model.ChatMsgListBean;
import com.ffapp.demo.chat.model.ChatMsgListData;
import com.ffapp.demo.chat.model.ChatSendMsgData;
import com.ffapp.demo.chat.stomp.StompUtils;
import com.ffapp.demo.map.GPSUtil;
import com.ffapp.demo.map.MapWechatAddressChoose;
import com.ffapp.demo.map.util.AMapUtil;
import com.ffapp.demo.util.MyUtils;
import com.ffapp.demo.util.ThreadUtils;
import com.ffapp.demo.view.BaseEditDialog;
import com.ffapp.demo.view.RecyclerItemView;
import com.ffapp.demo.view.SizeChangeRelativeLayout;
import com.lzf.easyfloat.EasyFloat;
import com.lzf.easyfloat.enums.ShowPattern;
import com.lzf.easyfloat.enums.SidePattern;
import com.lzf.easyfloat.interfaces.OnInvokeView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import io.reactivex.plugins.RxJavaPlugins;
import my.ActivityTool;
import my.FileUtils;
import my.ImageUtils;
import my.LogUtil;
import my.SystemParamsUtils;
import my.TimeUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;
import ua.naiksoftware.stomp.Stomp;
import ua.naiksoftware.stomp.StompClient;
import ua.naiksoftware.stomp.dto.StompHeader;

/**
 * 警情列表
 */
@SuppressLint({"HandlerLeak", "ClickableViewAccessibility"})
public class ChatGroupActivity extends BasisActivity {
    String TAG = StompUtils.TAG;

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.edit_input)
    EditText edit_input;
    @BindView(R.id.btn_add)
    ImageView btn_add;
    @BindView(R.id.view_more_zone)
    View view_more_zone;
    @BindView(R.id.recyclerview_more)
    RecyclerView recyclerview_more;
    @BindView(R.id.recyclerview_commonmsg)
    RecyclerView recyclerview_commonmsg;
    AdapterMore adapterMore;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    private AdapterChat mAdapter;

    String alarmId;
    String address_host = "";

    ChatMsgListBean mMsgListBean;
    StompClient stompClient;

    ChatMsgListBean mListHistoryMsg;

//    boolean isMoreMode = false;

    final static int MORE_MODE_DEFAULT = 0 ,MORE_MODE_MORE = 1,MORE_MODE_COMMONMSG = 2;
    private int more_mode = MORE_MODE_DEFAULT;

    public final String URL_SEND = "/api/v1/talkgroupMsg/send";

    @BindView(R.id.view_relatevelayout)
    SizeChangeRelativeLayout relativeLayout;
    @BindView(R.id.view_unreadmsg_count_zone)
    View view_unreadmsg_count_zone;
    @BindView(R.id.text_unread_msg_count)
    TextView text_unread_msg_count;

    private int mHistoryMsgCount;

    LinearLayoutManager mLinearLayoutManager;

    @Override
    public void initViews() {
        setDefautTrans(false);
        setContentView(R.layout.chat_activity);
        setTitle("讨论组");
        setTitleLeftButton(null);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        recyclerview.setLayoutManager(mLinearLayoutManager);
        recyclerview_more.setLayoutManager(new GridLayoutManager(mContext, 4));

        setTitleRightButton(R.drawable.top_icon_more, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("id", alarmId);
                ActivityTool.skipActivity(mContext, GroupInfoActivity.class, bundle);

//                mHistoryMsgCount = 25;
//                onUnReadMsgClick();
            }
        });
        edit_input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                switch (actionId){
                    case EditorInfo.IME_ACTION_SEND:
                        onSendClick();
                        break;
                    case EditorInfo.IME_ACTION_DONE:
                        break;
                    case EditorInfo.IME_ACTION_SEARCH:
                        break;
                }
                return true;
            }
        });

        edit_input.setOnKeyListener(new View.OnKeyListener() {
            @Override

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    scrollToTheBottom();
                }
                return false;
            }
        });
        scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (more_mode != MORE_MODE_DEFAULT) {
                    more_mode = MORE_MODE_DEFAULT;
                    setMoreModeView();

                }
                return false;
            }
        });
        recyclerview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (more_mode != MORE_MODE_DEFAULT) {
                    more_mode = MORE_MODE_DEFAULT;
                    setMoreModeView();
                }
                return false;
            }
        });

        relativeLayout.setOnResizeListener(new SizeChangeRelativeLayout.OnResizeListener() {
            @Override
            public void onResize(int w, int h, int oldw, int oldh) {
                LogUtil.i("relativeLayout--->h" + h + "-----oldh---:" + oldh);
                if (h < oldh) {
                    scrollView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.smoothScrollBy(0, (oldh - h));
                        }
                    }, 100);


//                    scrollToTheBottom();
                }
//                scrollToTheBottom();
//                if (h < oldh) {
////                    scrollView.smoothScrollBy(0,(oldh-h));
//
//                }
            }
        });
        if(LoginBean.isLogin() && LoginBean.getInstance().getUserInfo().isUserCompany() ){
            EasyFloat.with(this)
                    // 设置浮窗xml布局文件，并可设置详细信息
                    .setLayout(R.layout.user_float_view, new OnInvokeView() {
                        @Override
                        public void invoke(View view) {
                            ((TextView)view.findViewById(R.id.float_text_name)).setText(LoginBean.getInstance().getUserInfo().getName() + MyUtils.getPhoneLastFour(mContext));
//                            ((TextView)view.findViewById(R.id.float_text_mobile)).setText(new MySharedPreferences(mContext).getUser());
                        }
                    })
                    // 设置浮窗显示类型，默认只在当前Activity显示，可选一直显示、仅前台显示、仅后台显示
                    .setShowPattern(ShowPattern.CURRENT_ACTIVITY)
                    // 设置吸附方式，共15种模式，详情参考SidePattern
                    .setSidePattern(SidePattern.DEFAULT)
                    // 设置浮窗的标签，用于区分多个浮窗
                    .setTag("float")
                    // 设置浮窗是否可拖拽，默认可拖拽
                    .setDragEnable(false)
                    // 系统浮窗是否包含EditText，仅针对系统浮窗，默认不包含
                    .hasEditText(false)
                    // 设置浮窗固定坐标，ps：设置固定坐标，Gravity属性和offset属性将无效
//                    .setLocation(100, 200)
                    // 设置浮窗的对齐方式和坐标偏移量
                    .setGravity(Gravity.BOTTOM | Gravity.RIGHT, -30, -150)
                    // 设置宽高是否充满父布局，直接在xml设置match_parent属性无效
                    .setMatchParent(false, false)
                    // 设置Activity浮窗的出入动画，可自定义，实现相应接口即可（策略模式），无需动画直接设置为null
                    .setAnimator(null)
                    // 设置系统浮窗的出入动画，使用同上
                    .setAppFloatAnimator(null)
                    // 设置系统浮窗的不需要显示的页面
                    .show();
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        setNeedSign(false);
        super.initData(savedInstanceState);
        alarmId = getIntent().getStringExtra("id");
        if (TextUtils.isEmpty(alarmId)) {
            showToast("ID不存在");
            finish();
            return;
        }
        mMsgListBean = new ChatMsgListBean();
        setListView(false);

        address_host = MyUtils.getIp() + "/serv" + "/disposalsocket?type=talkgroup&alarmId=" + alarmId + "&userId=" + LoginBean.getUserId();
//        address_host = "ws://192.168.25.61:8012/disposalsocket?type=talkgroup&alarmId="+alarmId+"&userId="+ LoginBean.getUserId();
//        address_host = "http://192.168.25.61:8012/disposalsocket?type=talkgroup&alarmId="+alarmId+"&userId="+ LoginBean.getUserId();
//        address_host = MyUtils.getIp()+ ""+"/disposalsocket?type=talkgroup&alarmId="+alarmId+"&userId="+ LoginBean.getUserId();
        if (address_host.startsWith("http://192.") && address_host.contains("/serv/")) {
            address_host = address_host.replaceFirst("/serv/", "/");
        }

//        address_host = "ws://192.168.25.61:8012/disposalsocket";
//        address_host = "ws://121.40.165.18:8800";//http://www.websocket-test.com/测试用的websocket可连上
//        address_host = "ws://10.0.2.2:8080/example-endpoint/websocket";
        if(address_host.startsWith("http://")){
//            address_host = address_host.replace("http://","ws://");
        }
        if(address_host.startsWith("https://")){
            address_host = address_host.replace("https://","http://");
        }
        LogUtil.i(TAG, "address_host--->" + address_host);
//        initStom();

        btn_add.setVisibility(View.VISIBLE);

//        mHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                getHistoryMsg(false);
//            }
//        }, 1000);

        getUnreadMsgCount();
        getHistoryMsg(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(stompClient != null && stompClient.isConnected()){
            stompClient.disconnect();
            stompClient = null;
        }
    }

    @SuppressLint("CheckResult")
    void initStom() {
        if(isFinishing())return;
        stompClient = Stomp.over(Stomp.ConnectionProvider.OKHTTP, address_host);
//        StompClient stompClient = Stomp.over(Stomp.ConnectionProvider.JWS, address_host);
        LogUtil.i(TAG, "Start connecting to server");
//        StompUtils.lifecycle(stompClient);

        stompClient.lifecycle().subscribe(lifecycleEvent -> {
                    switch (lifecycleEvent.getType()) {
                        case OPENED:
                            LogUtil.i(TAG, "Stomp connection opened");
                            break;
                        case ERROR:
                            LogUtil.i(TAG, "Error---" + lifecycleEvent.getException());
                            break;
                        case CLOSED:
                            LogUtil.i(TAG, "Stomp connection closed");
                            mHandler.sendEmptyMessage(MSG_CONNECT_FAILED);
                            break;
                    }
                }
        );
        RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                LogUtil.i(TAG, "throwable==" + throwable.getMessage());
            }
        });
        stompClient.topic("/user/websocket/talkgroup/receive").subscribe(stompMessage -> {
            LogUtil.i(TAG, "Receive: " + stompMessage.getPayload());
            ArrayList<ChatMsgListData> arrayList = (ArrayList<ChatMsgListData>) JSONArray.parseArray(stompMessage.getPayload(), ChatMsgListData.class);
            ThreadUtils.doOnUIThread(new ThreadUtils.UITask() {
                @Override
                public void doOnUI() {
                    mMsgListBean.getList().addAll(arrayList);
                    setListView(true);
                }
            });
        });
        stompClient.connect();

//        stompClient.topic("/groupchat/someting").subscribe(stompMessage -> {
//            JSONObject jsonObject = new JSONObject(stompMessage.getPayload());
//            Log.i(Const.TAG, "Receive: " + jsonObject.toString());
//            runOnUiThread(() -> {
//                try {
//                    showText.append(jsonObject.getString("response") + "\n");
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            });
//        });
    }


    private void setListView(boolean isScrolltoBottom) {
        if (mAdapter == null) {
            mAdapter = new AdapterChat(mContext, mMsgListBean,mTopMoreClick);
            recyclerview.setAdapter(mAdapter);
        } else {
            mAdapter.setData(mMsgListBean);
        }
        if(isScrolltoBottom){
            scrollToTheBottom();
        }
    }
    AdapterChat.TopMoreClickListener mTopMoreClick = new AdapterChat.TopMoreClickListener() {
        @Override
        public void onTopMoreClick() {
            getHistoryMsg(true);
        }
    };

    void onSendClick() {
        String content = edit_input.getText().toString();
        if (TextUtils.isEmpty(content)) {
            showToast("请输入消息内容");
            return;
        }
        ChatSendMsgData sendMsgData = new ChatSendMsgData();
        sendMsgData.setAlarmId(alarmId);
        sendMsgData.setUserId(LoginBean.getUserId());
        sendMsgData.setType(ChatMsgListData.TYPE_TEXT);
        sendMsgData.setContent(content);

        if (!stompClient.isConnected()) {
            showToast("未连接服务器，正在尝试重新连接");
            mHandler.sendEmptyMessage(MSG_DISCONNECTED);
            return;
        }
        LogUtil.i(TAG, "----" + JSONObject.toJSONString(sendMsgData));
        List<StompHeader> list = new ArrayList<>();
//        StompMessage stompMessage = new StompMessage(URL_SEND, list, JSONObject.toJSONString(sendMsgData));
//        stompClient.send(stompMessage)
        stompClient.send(URL_SEND, JSONObject.toJSONString(sendMsgData)).subscribe();
        edit_input.setText("");
//        ViewUtils.hideInput(mContext, edit_input);
//        scrollToTheBottom();
//                .subscribe(new CompletableObserver() {
//            @Override
//            public void onSubscribe(Disposable d) {
//                LogUtil.i(TAG,"onSubscribe--->");
//            }
//
//            @Override
//            public void onComplete() {
//                LogUtil.i(TAG,"onComplete--->");
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                LogUtil.i(TAG,"onError--->"+e.getMessage());
//                e.printStackTrace();
//            }
//        });
//        stompClient.send("/api/v1/talkgroupMsg/send", JSONObject.toJSONString(sendMsgData));
    }

    void scrollToTheBottom() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
               edit_input.requestFocus();
            }
        }, 100);

    }
    void scrollToTheTop() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_UP);
            }
        }, 100);

    }

    private static final int MSG_DISCONNECTED = 91;
    private static final int MSG_CONNECT_FAILED = 92;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (isFinishing()) return;
            switch (msg.what) {
                case MSG_DISCONNECTED:
                    if (stompClient.isConnected()) return;
                    initStom();
                    break;
                case MSG_CONNECT_FAILED:
                    mHandler.removeMessages(MSG_CONNECT_FAILED);
                    mHandler.sendEmptyMessageDelayed(MSG_DISCONNECTED, 5000);
                    break;
            }
        }
    };

    private final static int REQUEST_IMG_GALLERY = 31
            , REQUEST_TAKE_PHOTO = 32
            , REQUEST_ADDRESS_CHOOSE = 33
            ;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_ADDRESS_CHOOSE){
            if(resultCode != Activity.RESULT_OK)return;
            PoiItem poiItem = data.getParcelableExtra("data");
            onPostLocation(poiItem);
//           showToast("分享位置："+ AMapUtil.getAddressNameFromPoiItem( poiItem));
        }
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
//                postImg(images.get(0), BusiTypeEmum.讨论组消息.getName());
                postImg(images.get(0), BusiTypeEmum.其他.getName());
            }
        }
    }

    void onPostLocation(PoiItem poiItem){
        ChatSendMsgData sendMsgData = new ChatSendMsgData();
        sendMsgData.setAlarmId(alarmId);
        sendMsgData.setUserId(LoginBean.getUserId());
        sendMsgData.setType(ChatMsgListData.TYPE_LOCATION);
        double[] location = GPSUtil.gcj02_To_Gps84(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude());
        sendMsgData.setContent(location[1]+","+location[0]);
        sendMsgData.setPositionName(poiItem.getTitle());
        sendMsgData.setPositionAddress(AMapUtil.getAddressDesFromPoiItem(poiItem));
        sendChatMsg(sendMsgData);
    }

    void getHistoryMsg(boolean isMore) {
        MyParams params = new MyParams();
        params.put(BaseListBeanXF.PAGE_NAME, "1");
        params.put(BaseListBeanXF.PAGE_SIZE_NAME, ChatMsgListBean.ONE_PAGE_SIZE);
        if (mMsgListBean != null && mMsgListBean.getList().size() > 0) {
            params.put("endTime", mMsgListBean.getList().get(0).getCreateTime());
        }else {
            params.put("endTime", TimeUtils.getCurrentTimeByFormat(TimeUtils.TIME_FOMART));
        }
        params.put("alarmId", alarmId);
        showProgress();
        MyHttpUtils.post(Constants.URL_CHAT_HISTORY_MSG, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        ChatMsgListBean bean = (ChatMsgListBean) result;
                        if(bean.getList().size() == 0){
                            if(isMore){
                                showToast("没有更多了");
                            }
                        }else {
                            mMsgListBean.getList().addAll(0, bean.getList());
                            mMsgListBean.sortByCreateTime();
                            setListView(!isMore);
                        }
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                        setListView(false);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                        if(!isMore){
                            initStom();
                        }
                    }
                },
                0, ChatMsgListBean.class);
    }

    @OnClick(R.id.btn_add)
    void onBtnAddClick() {
//        isMoreMode = !isMoreMode;
//        more_mode = MORE_MODE_MORE;
        switch (more_mode){
            case MORE_MODE_MORE:
                more_mode =MORE_MODE_DEFAULT;
                break;
            case MORE_MODE_DEFAULT:
                more_mode =MORE_MODE_MORE;
                break;
            case MORE_MODE_COMMONMSG:
                more_mode =MORE_MODE_MORE;
                break;
            default:
                more_mode =MORE_MODE_DEFAULT;
                break;
        }
        setMoreModeView();

    }

    void setMoreModeView() {
        switch (more_mode){
            case MORE_MODE_DEFAULT:
                view_more_zone.setVisibility(View.GONE);
                break;
            case MORE_MODE_MORE:
                view_more_zone.setVisibility(View.VISIBLE);
                recyclerview_commonmsg.setVisibility(View.GONE);
                recyclerview_more.setVisibility(View.VISIBLE);
                if (adapterMore == null) {
                    ArrayList<AdapterMore.MoreGridData> list = new ArrayList<>();
                    list.add(new AdapterMore.MoreGridData("相册", R.drawable.chat_icon_img));
                    list.add(new AdapterMore.MoreGridData("拍照", R.drawable.chat_icon_photo));
                    list.add(new AdapterMore.MoreGridData("分享位置", R.drawable.chat_icon_location));
                    list.add(new AdapterMore.MoreGridData("人员状态", R.drawable.chat_icon_man_status));
                    adapterMore = new AdapterMore(mContext, list, moreItemClickListener);
                    recyclerview_more.setAdapter(adapterMore);
                }
                break;
            case MORE_MODE_COMMONMSG:
                view_more_zone.setVisibility(View.VISIBLE);
                recyclerview_more.setVisibility(View.GONE);
                recyclerview_commonmsg.setVisibility(View.VISIBLE);
                setCommonMsgView();
                break;

        }
//        if (!isMoreMode) {
//
//        } else {
//            view_more_zone.setVisibility(View.VISIBLE);
//
//            if (adapterMore == null) {
//                ArrayList<AdapterMore.MoreGridData> list = new ArrayList<>();
//                list.add(new AdapterMore.MoreGridData("相册", R.drawable.chat_icon_img));
//                list.add(new AdapterMore.MoreGridData("拍照", R.drawable.chat_icon_photo));
//                list.add(new AdapterMore.MoreGridData("分享位置", R.drawable.chat_icon_location));
//                adapterMore = new AdapterMore(mContext, list, moreItemClickListener);
//                recyclerview_more.setAdapter(adapterMore);
//            }
//        }

    }

    MyAdapterCommonMsgList adapterCommonMsgList;
    private int currentCommonMsgPosition;

    @OnClick(R.id.btn_commonmsg)
    void onCommonMsgClick(){
//        more_mode = MORE_MODE_COMMONMSG;
        switch (more_mode){
            case MORE_MODE_MORE:
                more_mode =MORE_MODE_COMMONMSG;
                break;
            case MORE_MODE_DEFAULT:
                more_mode =MORE_MODE_COMMONMSG;
                break;
            case MORE_MODE_COMMONMSG:
                more_mode =MORE_MODE_DEFAULT;
                break;
            default:
                more_mode =MORE_MODE_DEFAULT;
                break;
        }


        setMoreModeView();
    }

    private void setCommonMsgView(){
        //作为一个ItemDecoration 写入的
        MyParams params = new MyParams();
        MyHttpUtils.post(Constants.URL_CHAT_FAST_INFO, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        CommonMsgListBean listBean = (CommonMsgListBean) result;
                        if(adapterCommonMsgList == null){
                            recyclerview_commonmsg.setLayoutManager(new LinearLayoutManager(mContext));
                            adapterCommonMsgList = new MyAdapterCommonMsgList(listBean);
                            recyclerview_commonmsg.setAdapter(adapterCommonMsgList);
                        }else {
                            adapterCommonMsgList.closeMenu();
                            adapterCommonMsgList.setData(listBean);
                        }
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                        dismissProgress();
                    }
                },
                0, CommonMsgListBean.class);
    }

    private void onCommonMsgReset(String msg,String id){
        BaseEditDialog dialog = new BaseEditDialog(mContext, new BaseEditDialog.OnEditPostListener() {
            @Override
            public void onEditPost(String name) {
                showLoading();
                MyParams params = new MyParams();
                params.put("id",id);
                params.put("content",name);
                MyHttpUtils.post(Constants.URL_CHAT_SAVE_INFO, params, new MyHttpListener() {
                            @Override
                            public void onSuccess(int httpWhat, Object result) {
                                setCommonMsgView();
                            }

                            @Override
                            public void onFinish(int httpWhat) {
                                dismissProgress();
                            }

                            @Override
                            public void onFailure(int httpWhat, Object result) {
                                super.onFailure(httpWhat, result);
                                dismissProgress();
                            }
                        },
                        0, BasisBean.class);

            }

            @Override
            public void onCancel() {

            }
        }, "添加常用语", "请填写添加常用语", "取消", "添加");
        dialog.setOrgString(msg);
        dialog.show();
    }

    private void onCommonMsgAdd(String msg,int position){
        currentCommonMsgPosition = position;
        BaseEditDialog dialog = new BaseEditDialog(mContext, new BaseEditDialog.OnEditPostListener() {
            @Override
            public void onEditPost(String name) {
                showLoading();
                MyParams params = new MyParams();
                params.put("content",name);
                MyHttpUtils.post(Constants.URL_CHAT_SAVE_INFO, params, new MyHttpListener() {
                            @Override
                            public void onSuccess(int httpWhat, Object result) {
                                setCommonMsgView();
                            }

                            @Override
                            public void onFailure(int httpWhat, Object result) {
                                super.onFailure(httpWhat, result);
                                dismissProgress();
                            }

                            @Override
                            public void onFinish(int httpWhat) {
                                dismissProgress();
                            }
                        },
                        0, BasisBean.class);

            }

            @Override
            public void onCancel() {

            }
        }, "添加常用语", "请填写添加常用语", "取消", "添加");
        dialog.setOrgString(msg);
        dialog.show();
    }
    private void onCommonMsgDelete(String id){
        showLoading();
        MyParams params = new MyParams();
        params.put("id",id);
        MyHttpUtils.post(Constants.URL_CHAT_DELETE_INFO, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        setCommonMsgView();
                    }

                    @Override
                    public void onFinish(int httpWhat) {

                    }
                },
                0, BasisBean.class);

    }
    private void onCommonMsgChoosed(String msg){
        sendContentMsg(msg);
//        more_mode = MORE_MODE_DEFAULT;
//        setMoreModeView();
//        edit_input.setText("");
    }
    private void sendContentMsg(String msg){
        ChatSendMsgData sendMsgData = new ChatSendMsgData();
        sendMsgData.setAlarmId(alarmId);
        sendMsgData.setUserId(LoginBean.getUserId());
        sendMsgData.setType(ChatMsgListData.TYPE_TEXT);
        sendMsgData.setContent(msg);

        if (!stompClient.isConnected()) {
            showToast("未连接服务器，正在尝试重新连接");
            mHandler.sendEmptyMessage(MSG_DISCONNECTED);
            return;
        }
        LogUtil.i(TAG, "----" + JSONObject.toJSONString(sendMsgData));
        List<StompHeader> list = new ArrayList<>();
//        StompMessage stompMessage = new StompMessage(URL_SEND, list, JSONObject.toJSONString(sendMsgData));
//        stompClient.send(stompMessage)
        stompClient.send(URL_SEND, JSONObject.toJSONString(sendMsgData)).subscribe();
//        more_mode = MORE_MODE_DEFAULT;
//        setMoreModeView();
//        edit_input.setText("");
    }

    private void sendUserStateMsg(String msg){
        ChatSendMsgData sendMsgData = new ChatSendMsgData();
        sendMsgData.setAlarmId(alarmId);
        sendMsgData.setUserId(LoginBean.getUserId());
        sendMsgData.setType(ChatMsgListData.TYPE_USERSTATE);
        sendMsgData.setContent(msg);

        if (!stompClient.isConnected()) {
            showToast("未连接服务器，正在尝试重新连接");
            mHandler.sendEmptyMessage(MSG_DISCONNECTED);
            return;
        }
        LogUtil.i(TAG, "----" + JSONObject.toJSONString(sendMsgData));
        List<StompHeader> list = new ArrayList<>();
//        StompMessage stompMessage = new StompMessage(URL_SEND, list, JSONObject.toJSONString(sendMsgData));
//        stompClient.send(stompMessage)
        stompClient.send(URL_SEND, JSONObject.toJSONString(sendMsgData)).subscribe();
//        more_mode = MORE_MODE_DEFAULT;
//        setMoreModeView();
//        edit_input.setText("");
    }



    AdapterMore.MoreItemClickListener moreItemClickListener = new AdapterMore.MoreItemClickListener() {
        @Override
        public void onItemClick(AdapterMore.MoreGridData data) {
            Intent intent;
            switch (data.getName()) {
                case "相册":
//                    ImagePicker.getInstance().setSelectLimit(1);
                    ImagePicker.getInstance().setMultiMode(false);
                    intent = new Intent(mContext, ImageGridActivity.class);
                    mContext.startActivityForResult(intent, REQUEST_IMG_GALLERY);
                    break;
                case "拍照":
                    intent = new Intent(mContext, ImageGridActivity.class);
                    intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                    startActivityForResult(intent, REQUEST_IMG_GALLERY);
//                    ImagePicker.getInstance().setSelectLimit(1);
//                     intent = new Intent(mContext, ImageGridActivity.class);
//                    mContext.startActivityForResult(intent, REQUEST_IMG_GALLERY);
                    break;
                case "分享位置":
//                  ActivityTool.skipActivityForResult(mContext, MapAddressChoose.class,REQUEST_ADDRESS_CHOOSE);
                    MapWechatAddressChoose.toMapAddressChoose(mContext,"分享位置",REQUEST_ADDRESS_CHOOSE);
//                    ImagePicker.getInstance().setSelectLimit(1);
//                     intent = new Intent(mContext, ImageGridActivity.class);
//                    mContext.startActivityForResult(intent, REQUEST_IMG_GALLERY);
                    break;
                case "人员状态":
                    more_mode = MORE_MODE_DEFAULT;
                    setMoreModeView();
                    DialogPeopleStatus dialog= new DialogPeopleStatus(mContext, new DialogPeopleStatus.onPeopleStatusEditListener() {
                        @Override
                        public void onPost(String content) {
                            sendUserStateMsg(content);
                        }
                        @Override
                        public void onCancel() {
                        }

                        @Override
                        public void onToast(String mes) {
                            showToast(mes);
                        }
                    });
                    dialog.show();
                    break;
            }
        }
    };

    private void postImg(ImageItem imgData, String busytype) {
//        LogUtil.i("postImg----->"+request_code+"------>"+imgData.getFilePath());
        String filepathTemp = imgData.path;
        if (FileUtils.isFileImg(filepathTemp)) {
            filepathTemp = Constants.DIR_TEMP + FileUtils.getFileNameByPath(filepathTemp);
            ImageUtils.savePicToSdcard(ImageUtils.getBitmapBySize(imgData.path, 1000, 1000), Constants.DIR_TEMP, FileUtils.getFileNameByPath(imgData.path));
        }

        MyParams params = new MyParams();
        params.add("busiType", busytype);
        params.put("files", new File(filepathTemp));
        params.put("fileType", FileTypeEmum.Image);
//        params.put("dataOrder", "");

        showLoading();
        MyHttpUtils.postFile(Constants.URL_USER_ATTACHMENT_UPLOAD, params, new MyHttpListener() {
            @Override
            public void onSuccess(int httpWhat, Object result) {
                UserUploadFileListBean listBean = (UserUploadFileListBean) result;
//                String imgId = listBean.getImgIdFirst();
                sendImgMsg(listBean.getList().get(0));
            }

            @Override
            public void onFinish(int httpWhat) {
                dismissProgress();
            }
        }, UserUploadFileListBean.class);

    }

    private void sendImgMsg(UserUploadFileBean uploadFileBean) {
        ChatSendMsgData sendMsgData = new ChatSendMsgData();
        sendMsgData.setAlarmId(alarmId);
        sendMsgData.setUserId(LoginBean.getUserId());
        sendMsgData.setType(ChatMsgListData.TYPE_IMAGE);
        sendMsgData.setContent(uploadFileBean.getFilePath());
        sendMsgData.setAttachmentId(uploadFileBean.getId());

        sendChatMsg(sendMsgData);

//        if (!stompClient.isConnected()) {
//            showToast("未连接服务器，正在尝试重新连接");
//            mHandler.sendEmptyMessage(MSG_DISCONNECTED);
//            return;
//        }
//        LogUtil.i(TAG, "----" + JSONObject.toJSONString(sendMsgData));
//        List<StompHeader> list = new ArrayList<>();
//        StompMessage stompMessage = new StompMessage(URL_SEND, list, JSONObject.toJSONString(sendMsgData));
////        stompClient.send(stompMessage)
//        stompClient.send(URL_SEND, JSONObject.toJSONString(sendMsgData)).subscribe();
    }

    private void sendChatMsg(ChatSendMsgData sendMsgData) {
        if (!stompClient.isConnected()) {
            showToast("未连接服务器，正在尝试重新连接");
            mHandler.sendEmptyMessage(MSG_DISCONNECTED);
            return;
        }
        LogUtil.i(TAG, "----" + JSONObject.toJSONString(sendMsgData));
//        stompClient.send(stompMessage)
        stompClient.send(URL_SEND, JSONObject.toJSONString(sendMsgData)).subscribe();
    }



    void getUnreadMsgCount() {
//        initStom();
        MyParams params = new MyParams();
            params.put("endTime", TimeUtils.getCurrentTimeByFormat(TimeUtils.TIME_FOMART));
        params.put("alarmId", alarmId);
        showProgress();
        MyHttpUtils.post(Constants.URL_CHAT_UNREAD_MSG_COUNT, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        BasisBean bean = (BasisBean) result;
                        String msgCountStr = bean.getResultData();
                        mHistoryMsgCount = 0;
                        try {
                            mHistoryMsgCount = Integer.valueOf(msgCountStr);
                        }catch (Exception e){

                        }
                        if(mHistoryMsgCount == 0 || mHistoryMsgCount < 10){
                            view_unreadmsg_count_zone.setVisibility(View.GONE);
                        }else {
                            view_unreadmsg_count_zone.setVisibility(View.VISIBLE);
                            if(mHistoryMsgCount > 100){
                                text_unread_msg_count.setText(mHistoryMsgCount+"条新消息");
                            }else {
                                text_unread_msg_count.setText(mHistoryMsgCount+"条新消息");
                            }

                        }
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                        setListView(false);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, BasisBean.class);
    }

    @OnClick(R.id.view_unreadmsg_count_zone)
    void onUnReadMsgClick(){
//        scrollToTheTop();

        LogUtil.i("onUnReadMsgClick---->"+mHistoryMsgCount);
        view_unreadmsg_count_zone.setVisibility(View.GONE);
        if(mHistoryMsgCount > 0){
            int toPosition = 0;
            if(mMsgListBean.getList().size() < mHistoryMsgCount){
                toPosition = 0;
            }else {
                toPosition = mMsgListBean.getList().size() -mHistoryMsgCount;
            }
            if( mLinearLayoutManager.findViewByPosition(toPosition) != null){
                int scrollPosition =  mLinearLayoutManager.findViewByPosition(toPosition).getTop();
                //            LogUtil.i("scrollPosition---->"+scrollPosition);
//            LogUtil.i("scrollPosition---->"+mLinearLayoutManager.findViewByPosition(toPosition).getBottom());
                scrollView.scrollTo(0,scrollPosition);
            }


//            recyclerview.scrollToPosition(toPosition);
        }
    }


    public class MyAdapterCommonMsgList extends RecyclerView.Adapter<MyAdapterCommonMsgList.ViewHolder> implements RecyclerItemView.onSlidingButtonListener  {

        private CommonMsgListBean listBean;

//        private onSlidingViewClickListener onSvcl;
        private RecyclerItemView recyclers;

        public MyAdapterCommonMsgList(CommonMsgListBean list) {
            listBean = list;
        }

        public void setData(CommonMsgListBean list){
            listBean = list;
            notifyDataSetChanged();
        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            if(viewType == 1){
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.chat_commonmsg_list_more_item, viewGroup, false);
                return new ViewHolder(view,viewType);
            }else {
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.chat_commonmsg_list_item, viewGroup, false);
                return new ViewHolder(view,viewType);
            }

        }

        @Override
        public int getItemViewType(int position) {
            if(position == getItemCount() -1)return  1;
            return super.getItemViewType(position);
        }

        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            if(position == getItemCount() -1){

            }else {
                viewHolder.bind(position);
            }
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return listBean == null ? 1 : listBean.getList().size()+1;
        }

        @Override
        public void onMenuIsOpen(View view) {
            recyclers = (RecyclerItemView) view;
        }

        @Override
        public void onDownOrMove(RecyclerItemView recycler) {
            if(menuIsOpen()){
                if(recyclers != recycler){
                    closeMenu();
                }
            }
        }

        //关闭菜单
        public void closeMenu() {
            if(recyclers != null){
                recyclers.closeMenu();
                recyclers = null;
            }
        }

        // 判断是否有菜单打开
        public Boolean menuIsOpen() {
            if(recyclers != null){
                return true;
            }
            return false;
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder  {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_title)
            public TextView text_title;
            @BindView(R.id.btn_delete)
            public View btn_delete;
            @BindView(R.id.btn_edit)
            public View btn_edit;
            @BindView(R.id.view_add_zone)
            public View view_add_zone;
            @BindView(R.id.slide)
            public View slide;
            @BindView(R.id.view_main)
            public View view_main;

            public ViewHolder(View view,int type) {
                super(view);
                if(type == 1){
                    view_add_zone = view.findViewById(R.id.view_add_zone);
                    view_add_zone.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onItemAddClick(v);
                        }
                    });
                }else {
                    ButterKnife.bind(this, view);
                    view_main.getLayoutParams().width = SystemParamsUtils.getScreenWidth();

                    ((RecyclerItemView)view).setSlidingButtonListener(MyAdapterCommonMsgList.this);
                }


            }

            public void bind(int position) {
                if(position == getItemCount() -1){
                    view_add_zone.setVisibility(View.VISIBLE);
                    list_item.setVisibility(View.GONE);
                }else {
                    CommonMsgListData listData = listBean.getList().get(position);
                    view_add_zone.setVisibility(View.GONE);
                    list_item.setVisibility(View.VISIBLE);
                    String data = listData.getContent();
                    text_title.setText(data);

                    btn_edit.setTag(position);
                    btn_delete.setTag(position);
                }

                view_main.setTag(R.id.img_tag,position);
            }


            @OnClick({R.id.view_main})
            public void onItemClick(View v) {
                int position = (int) v.getTag(R.id.img_tag);
                String data = listBean.getList().get(position).getContent();
                onCommonMsgChoosed(data);
            }

            @OnClick({R.id.btn_edit})
            public void onBtnEditClick(View v) {
                int position = (int) v.getTag();
                CommonMsgListData data = listBean.getList().get(position);
                onCommonMsgReset(data.getContent(),data.getId());
            }

            @OnClick({R.id.btn_delete})
            public void onBtnDeleteClick(View v) {
                int position = (int) v.getTag();
                new QMUIDialog.MessageDialogBuilder(mContext).setMessage("是否删除常用语").addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                }).addAction(0, "删除", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        onCommonMsgDelete(listBean.getList().get(position).getId());
                        dialog.dismiss();
                    }
                }).create().show();

            }

//            @OnClick({R.id.view_add_zone})
            public void onItemAddClick(View v) {
                onCommonMsgAdd("",getItemCount()-1);
            }

//            @Override
//            public float getActionWidth() {
//                LogUtil.i("getActionWidth----->"+slide.getWidth() );
//                return slide.getWidth();
////                return DisplayUtil.dip2px(mContext,120);
//            }
//
//            @Override
//            public View ItemView() {
//                LogUtil.i("ItemView----->" );
//                return item_view;
//            }
        }

        public class ViewHolderMore extends ViewHolder  {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.view_add_zone)
            public View view_add_zone;

            public ViewHolderMore(View view) {
                super(view,1);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
            }

            @OnClick({R.id.view_add_zone})
            public void onItemAddClick(View v) {
                onCommonMsgAdd("",getItemCount()-1);
            }

        }
    }

}
